﻿using System;
using System.IO.Compression;
using System.Web;
using System.Web.UI;

namespace WhoAmI
{
	public partial class _Default : System.Web.UI.Page
	{
		protected override void OnPreInit(EventArgs e)
		{
			base.OnPreInit(e);

			this.lblIpAddress.Text = this.GetIpAddress();
			this.lblPlatform.Text = this.Request.Browser.Platform;
			this.lblUserAgent.Text = this.Request.ServerVariables["HTTP_USER_AGENT"];
			this.lblScreenResolution.Text = this.GetNoScript();
		}

		protected override void Render(HtmlTextWriter writer)
		{
			HttpContext context = HttpContext.Current;
			HttpRequest request = context.Request;
			string acceptEncoding = request.Headers["Accept-Encoding"];
			HttpResponse response = context.Response;
			if (!string.IsNullOrEmpty(acceptEncoding))
			{
				acceptEncoding = acceptEncoding.ToUpperInvariant();
				response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
				if (acceptEncoding.Contains("GZIP"))
				{
					response.AppendHeader("Content-encoding", "gzip");
				}
				else if (acceptEncoding.Contains("DEFLATE"))
				{
					response.AppendHeader("Content-encoding", "deflate");
				}
			}

			response.Cache.VaryByHeaders["Accept-Encoding"] = true;

			base.Render(writer);
		}

		private string GetIpAddress()
		{
			string remoteAddress = this.Request.ServerVariables["REMOTE_ADDR"];
			string remoteHost = this.Request.ServerVariables["REMOTE_HOST"];
			string result = this.Request.ServerVariables["REMOTE_ADDR"];

			if (!string.IsNullOrEmpty(remoteHost)
				&& remoteHost != remoteAddress)
			{
				result += "<br />" + remoteHost;
			}

			return result;
		}

		private string GetNoScript()
		{
			return "<noscript>JavaScript disabled!</noscript>";
		}
	}
}
